package servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			// 初始化smartUpload对象
			SmartUpload smartUpload = new SmartUpload();
			// 获取pageContext
			PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
			// 初始化smartUpload
			smartUpload.initialize(pageContext);
			// 设置编码方式
			smartUpload.setCharset("utf-8");
			// 上传
			smartUpload.upload();
			// 获取文件信息
			File file = smartUpload.getFiles().getFile(0);
			String name = smartUpload.getRequest().getParameter("name");
			String ext = file.getFileExt();
			name = name+"."+ext;
			String uploadPath = "/files/"+name;
			// 保存文件
			file.saveAs(uploadPath,File.SAVEAS_VIRTUAL);

			// 作用域存值
			req.setAttribute("fileName",name);
			req.getRequestDispatcher("success.jsp").forward(req,resp);
		} catch (SmartUploadException e) {
			e.printStackTrace();
		}
	}
}
